package per.songyu.pj.goods.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import per.songyu.pj.goods.dao.GoodsDao;
import per.songyu.pj.goods.pojo.Goods;
import per.songyu.pj.goods.service.GoodsService;

import javax.annotation.PostConstruct;
import java.util.List;

@Controller
@RequestMapping("/goods/")
public class GoodsController {

//    @Autowired
//    GoodsDao goodsDao;
//
//    @RequestMapping("/findGoods")
//    public List<Goods> findGoods(){
//        return goodsDao.findGoods();
//    }

    @Autowired //has a
    private GoodsService goodsService;

    @RequestMapping("doGoodsUI")
    public String doGoodsUI(Model model){
        List<Goods> goodsList=goodsService.findGoods();
        model.addAttribute("goodsList", goodsList);
        return "goods";//viewname
        //返回值会交给DispatcherServlet进行处理
        //DispatcherServlet会调用ViewResolver进行视图解析(view+model)
        //最后DispatcherServlet将解析结果响应到页面上
    }

    @RequestMapping("doGoodsUpdateUI/{id}")
    public String doGoodsUpdateUI(Model model,@PathVariable int id){
        Goods goodsList=goodsService.findGoodsById(id);
        model.addAttribute("goodsList", goodsList);
        return "goods-update";//viewname
        //返回值会交给DispatcherServlet进行处理
        //DispatcherServlet会调用ViewResolver进行视图解析(view+model)
        //最后DispatcherServlet将解析结果响应到页面上
    }

    @PostMapping("doGoodsUpdate")
    public String doGoodsUpdate(Model model, Goods goods){
        goodsService.doUpdateById(goods);
        return "redirect:/goods/doGoodsUI";//viewname
        //返回值会交给DispatcherServlet进行处理
        //DispatcherServlet会调用ViewResolver进行视图解析(view+model)
        //最后DispatcherServlet将解析结果响应到页面上
    }

    @RequestMapping("doGoodsAddUI")
    public String doGoodsAddUI(){

        return "goods-add";//viewname
        //返回值会交给DispatcherServlet进行处理
        //DispatcherServlet会调用ViewResolver进行视图解析(view+model)
        //最后DispatcherServlet将解析结果响应到页面上
    }

    @RequestMapping("doGoodsAdd")
    public String doGoodsAdd(Goods entity){
        goodsService.saveGoods(entity);
        return "redirect:/goods/doGoodsUI";//viewname
        //返回值会交给DispatcherServlet进行处理
        //DispatcherServlet会调用ViewResolver进行视图解析(view+model)
        //最后DispatcherServlet将解析结果响应到页面上
    }

    @RequestMapping("doDeleteById/{id}")
    public String doDeleteById(@PathVariable Integer id){
        goodsService.doDeleteById(id);
        return "redirect:/goods/doGoodsUI";
    }
}
